/**
 * @author 陈泰来
 * @version V1.0
 * @Project echo-java-base
 * @Title 手写生产者消费者2
 * @Description *
 * @Package concurrent.blockingQueue.BQtest2
 * @date 2021/3/22 3:22 下午
 * @Copyright:学如逆水行舟，不进则退 .
 */
package concurrent.blockingQueue.bqtest2;

import java.text.MessageFormat;
import java.util.Objects;
import java.util.concurrent.BlockingDeque;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.atomic.AtomicInteger;

public class DoubleEndedDeque<T> {

    //阻塞双端列表
    BlockingDeque<T> blockingDeque;

    volatile AtomicInteger consumerMsgNum = new AtomicInteger();

    volatile AtomicInteger produceMsgNum = new AtomicInteger();

    public DoubleEndedDeque(BlockingDeque<T> blockingDeque) {
        this.blockingDeque = blockingDeque;
    }

    /**
     * 推送
     */
    public void push(T msg) {
        try {
            blockingDeque.putFirst(msg);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            System.out.printf("生产者 推送一条消息: %s  \n", msg.toString());
            System.out.println(MessageFormat.format("生产消息总数:{0}", produceMsgNum.getAndIncrement()));

        }

    }

    /**
     * 读取一条消息
     */
    public void take() {
        T msg = null;
        try {
            msg = blockingDeque.poll();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (!Objects.isNull(msg)) System.out.printf("消费者 读取一条消息: %s \n", msg.toString());
            System.out.println(MessageFormat.format("消费消息总数:{0}", consumerMsgNum.getAndIncrement()));

        }
    }

    public static void main(String[] args) {
        DoubleEndedDeque<String> blockingDeque = new DoubleEndedDeque<>(new LinkedBlockingDeque<>(10));

        Thread consumer = new Thread(new Consumer(blockingDeque));
        Thread producer = new Thread(new Producer(blockingDeque));

        producer.start();
        consumer.start();
    }

}
